/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tfb.service.utility;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonNode;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.tlr.TlrDeviceException;
import com.tlr.device.rest.AppContext;

public class HttpUtil implements AppConst {

    private static final Log log = LogFactory.getLog(HttpUtil.class);

    public static CloseableHttpClient createHttpClient() {
        if (AppContext.isProxyEnabled()) {
            HttpHost proxy = new HttpHost(AppContext.getHttpAddress(), AppContext.getProxyPort());
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            return HttpClients.custom().setRoutePlanner(routePlanner).build();
        }
        return HttpClients.createDefault();
    }

    public static String getCookieOpenID(HttpServletRequest httpRequest) {
        Cookie[] cookies = httpRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (USER_OPEN_ID.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return "";
    }

    public static String getUserDBID(HttpServletRequest request) {
        Object userDBID = HttpUtil.getCookieUserDBID(request);
        log.info("cookie userID: " + String.valueOf(userDBID));
        if (userDBID == null) {
            request.getSession().getAttribute(AppConst.USER_DB_ID);
            log.info("session userID: " + String.valueOf(userDBID));
        }
        if (userDBID == null) {
            throw new TlrDeviceException("会话过期，请关闭页面重新访问");
        }
        return userDBID.toString();
    }

    public static String getCookieTarget(HttpServletRequest httpRequest) {
        Cookie[] cookies = httpRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (TARGET_NAME.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return "users";
    }

    public static String getCookieUserDBID(HttpServletRequest httpRequest) {
        Cookie[] cookies = httpRequest.getCookies();
        for (Cookie cookie : cookies) {
            log.info("cookie=" + cookie.getName() + ",maxAge=" + cookie.getMaxAge());
            if (USER_DB_ID.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    public static String getWechatOpenID(String code) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String getAccessTokenUrl = String.format(GET_CODE_ACCESS_TOKEN, code);
            HttpGet httpGet = new HttpGet(getAccessTokenUrl);
            try (CloseableHttpResponse accessTokenResp = httpClient.execute(httpGet)) {
                String openIDJson = EntityUtils.toString(accessTokenResp.getEntity(), "UTF-8");
                // GET open ID
                log.info("OpenIDJson: " + openIDJson);
                JsonNode accessTokenNode = JsonUtil.createJson(openIDJson);
                return accessTokenNode.has("openid") ? accessTokenNode.get("openid").asText() : null;
            }
        }
    }

    public static JsonNode getUserBasicInfo(String openID) {
        Client client = Client.create();
        String userBaseInfoUrl = String.format(USER_BASE_INFO_GET, AppContext.getWechatAccessToken(), openID);
        WebResource webResource = client.resource(userBaseInfoUrl);
        String content = webResource.accept(MediaType.APPLICATION_JSON).get(String.class);
        JsonNode userBaseInfoNode = JsonUtil.createJson(content);
        return userBaseInfoNode;
    }
}
